package org.punkgrok.flightrecorder;

import org.punkgrok.flightrecorder.MethodInvocation;
import org.punkgrok.flightrecorder.struts.ExceptionalActionServlet;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedList;
import java.util.List;

/**
 * User: Roman Florian Zabicki III
 * Date: May 25, 2009
 * Time: 2:26:18 PM
 */
public class HttpServletRequestInvocationHandler implements InvocationHandler {
	private HttpServletRequest wrapped;
	private List<MethodInvocation> invokedMethods;

	public HttpServletRequestInvocationHandler(HttpServletRequest wrapped) {
		this.wrapped = wrapped;
		invokedMethods = new LinkedList<MethodInvocation>();
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object returnValue = method.invoke(wrapped, args);

		invokedMethods.add(new MethodInvocation(method.getName(), args, returnValue));

		return returnValue;
	}

	public List<MethodInvocation> getInvokedMethods() {
		return invokedMethods;
	}

	public static HttpServletRequest buildProxy(HttpServletRequest request) {
		HttpServletRequestInvocationHandler handler = new HttpServletRequestInvocationHandler(request);
		return (HttpServletRequest) Proxy.newProxyInstance(ExceptionalActionServlet.class.getClassLoader(),
			new Class[]{HttpServletRequest.class},
			handler);
	}
}
